var list = []
var app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    images_arr: [],
    destination: '', //目的地
    destinationId: '',
    driverName: '', //司机姓名
    driverNameId: '',
    drivingCard: '', //车牌号
    //
    categoryStatus: false,
    objectMultiArray: [],
    multiIndex: [0, 0],
    multiArray: [],
    categoryName: '',
    categoryIdOne: '',
    categoryIdTwo: '',
    //
    weightOne: '', //毛重
    weightTwo: '', //车重
    weight: '', //货重
    packetNum: '', //包数数量
    buthidden: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this
    this.getOne()
  },
  getOne() {
    var that = this
    wx.showLoading({
      title: '拼命加载中'
    })
    wx.request({
      method: 'POST',
      url: app.preUrl + 'getListCategory',
      dataType: 'json',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        userId: app.globalData.userId
      },
      success: function(res) {
        wx.hideLoading()
        let data = res.data.result
        console.log(res.data.result)
        let arrO = []
        let arrT = []
        data.forEach((item, index) => {
          arrO.push(item.name)
        })
        data[0].categoryList.forEach((item, index) => {
          arrT.push(item.name)
        })
        let newmultiArray = [arrO, arrT]
        console.log(newmultiArray)
        that.setData({
          objectMultiArray: res.data.result,
          multiArray: newmultiArray
        })
      },
      fail: function(error) {
        console.log(error)
      }
    })
  },
  //品类选择
  bindMultiPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    var that = this
    that.setData({
      multiIndex: e.detail.value,
      categoryStatus: true,
      categoryIdOne: that.data.objectMultiArray[e.detail.value[0]].categoryId,
      categoryIdTwo:
        that.data.objectMultiArray[e.detail.value[0]].categoryList[
          e.detail.value[1]
        ].categoryId,
      categoryName:
        that.data.objectMultiArray[e.detail.value[0]].categoryList[
          e.detail.value[1]
        ].name
    })
    console.log(this.data.multiIndex)
    console.log(that.data.objectMultiArray[e.detail.value[0]].categoryId) //一级品类id
    console.log(
      that.data.objectMultiArray[e.detail.value[0]].categoryList[
        e.detail.value[1]
      ].categoryId
    ) //二级品类id
  },
  bindMultiPickerColumnChange: function(e) {
    var that = this
    console.log('修改的列为', e.detail.column, '，值为', e.detail.value)

    switch (e.detail.column) {
      case 0:
        list = []
        for (var i = 0; i < that.data.objectMultiArray.length; i++) {
          if (
            that.data.objectMultiArray[i].categoryId ==
            that.data.objectMultiArray[e.detail.value].categoryId
          ) {
            for (
              let j = 0;
              j < that.data.objectMultiArray[i].categoryList.length;
              j++
            ) {
              list.push(that.data.objectMultiArray[i].categoryList[j].name)
            }
          }
        }
        that.setData({
          'multiArray[1]': list,
          'multiIndex[0]': e.detail.value,
          'multiIndex[1]': 0
        })
    }
  },
  //录入重量
  onNumberWeightOne: function(e) {
    var that = this
    that.setData({ weightOne: e.detail.value.replace(/[^\d.]/g, '') })
    that.setData({ weightOne: e.detail.value.replace(/\.{2,}/g, '.') })
    that.setData({
      weightOne: e.detail.value
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
    })
    that.setData({
      weightOne: e.detail.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
    })

    this.onWeight()
  },

  //录入重量
  onNumberWeightTwo: function(e) {
    var that = this
    that.setData({ weightTwo: e.detail.value.replace(/[^\d.]/g, '') })
    that.setData({ weightTwo: e.detail.value.replace(/\.{2,}/g, '.') })
    that.setData({
      weightTwo: e.detail.value
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
    })
    that.setData({
      weightTwo: e.detail.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
    })
    this.onWeight()
  },
  // 货重
  onWeight() {
    let weightOne = Number(this.data.weightOne)
    let weightTwo = Number(this.data.weightTwo)
    let weight = (weightOne - weightTwo).toFixed(2)
    if (weight < 0) {
      this.setData({
        weight: 0
      })
    } else {
      this.setData({
        weight: (weightOne - weightTwo).toFixed(2)
      })
    }
  },
  //录入包数数量
  onNumber: function(e) {
    var that = this
    that.setData({ packetNum: e.detail.value.replace(/[^\d.]/g, '') })
    that.setData({ packetNum: e.detail.value.replace(/\.{2,}/g, '.') })
    that.setData({
      packetNum: e.detail.value
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
    })
    that.setData({
      packetNum: e.detail.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
    })
  },
  upload: function(item) {
    var that = this
    wx.showLoading({
      title: '上传中'
    })
    wx.uploadFile({
      url: app.preUrl + 'uploadFile',
      header: {
        'Content-Type': 'multipart/form-data'
      },
      filePath: item,
      name: 'file',
      formData: {
        userId: app.globalData.userId //附加信息为用户ID
      },
      success: function(res) {
        console.log(res)
        wx.hideLoading()
        var imgUrl =
          'https://www.lvdaxia.com.cn/dabaozhan/fileImage/' +
          JSON.parse(res.data).result
        that.setData({
          images_arr: that.data.images_arr.concat(imgUrl)
        })
      }
    })
  },
  upimg: function() {
    let that = this
    let len = 0
    len = 4 - this.data.images_arr.length
    if (len == 0) {
      wx.showToast({
        title: '最多上传4张图片',
        icon: 'loading',
        duration: 1500
      })
      return
    }
    wx.chooseImage({
      count: len,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        const tempFilePaths = res.tempFilePaths
        console.log(res)
        tempFilePaths.forEach(function(item, index) {
          that.upload(item)
        })
      }
    })
  },

  // 删除图片
  deleteImg: function(e) {
    var that = this
    var images = that.data.images_arr
    var index = e.currentTarget.dataset.index
    images.splice(index, 1)
    that.setData({
      images_arr: images
    })
  },

  bindFormSubmit() {
    var that = this
    var destination = that.data.destination
    var drivingCard = that.data.drivingCard
    var weightOne = that.data.weightOne
    var weigtTwo = that.data.weightTwo
    var weight = that.data.weight
    var packetNum = that.data.packetNum
    if (!destination) {
      wx.showToast({
        title: '目的地必填',
        icon: 'none'
      })
      return false
    } else if (!drivingCard) {
      wx.showToast({
        title: '车牌号必填',
        icon: 'none'
      })
      return false
    } else if (!that.data.categoryStatus) {
      wx.showToast({
        title: '回收类别必选',
        icon: 'none'
      })
      return false
    } else if (!weightOne) {
      wx.showToast({
        title: '毛重必填',
        icon: 'none'
      })
      return false
    } else if (!weigtTwo) {
      wx.showToast({
        title: '车重必填',
        icon: 'none'
      })
      return false
    } else if (weight <= 0) {
      wx.showToast({
        title: '货重不正确',
        icon: 'none'
      })
      return false
    } else if (!packetNum) {
      wx.showToast({ title: '包数必填', icon: 'none' })
      return false
    } else {
      wx.showLoading({ title: '提交中' })
      that.setData({ buthidden: true })
      wx.request({
        method: 'POST',
        url: app.preUrl + 'outSite',
        dataType: 'json',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          userId: app.globalData.userId,
          siteFactoryId: that.data.destinationId, //目的地ID
          siteVehicleId: that.data.driverNameId, //司机ID
          parentId: that.data.categoryIdOne, //品类父类ID
          categoryId: that.data.categoryIdTwo, //品类ID
          categoryName: that.data.categoryName, //品类名称
          grossWeight: weightOne,
          tareWeight: weigtTwo,
          cargoWeight: weight,
          packetNumber: packetNum,
          pictureList: that.data.images_arr
        },
        success: function(res) {
          wx.hideLoading()
          console.log(res)
          if (res.data.code == 100) {
            wx.showToast({
              title: '发布成功',
              icon: 'success',
              duration: 1000
            })
            setTimeout(function() {
              wx.navigateBack({
                delta: 1
              })
            }, 1500)
          } else {
            wx.showModal({
              title: '提示',
              content: res.data.message,
              confirmColor: '#56BDE0',
              showCancel: false
            })
            that.setData({ buthidden: false })
          }
        },
        fail: function(error) {
          console.log(error)
          that.setData({ buthidden: false })
        }
      })
    }
  },
  goCar() {
    wx.navigateTo({
      url: 'carManage'
    })
  },
  goFactory() {
    wx.navigateTo({
      url: 'factoryManage'
    })
  }
})
